﻿#include "bubble.h"
#include "ui_bubble.h"

Bubble::Bubble(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Bubble)
{
    ui->setupUi(this);
}

Bubble::~Bubble()
{
    delete ui;
}

void Bubble::setContent(int avatar, const QString &text, const QString &time, int width)
{
    is_text = true;
    QString imagePath;
    imagePath = ":/icon/avatar/" + QString::number(avatar);
    QImage ava(imagePath);

    ui->LAavatar->setPixmap(QPixmap::fromImage(ava));
    ui->LAtext->setWordWrap(true);
    ui->LAtext->setText(text);
    ui->LAtime->setText(time);
    ui->LAtext->resize(QSize(width, height()));
}

void Bubble::setPicture(int avatar, const QString& picPath, const QString& time, int width) {
    is_text = false;
    QString imagePath;
    imagePath = ":/icon/avatar/" + QString::number(avatar);
    QImage ava(imagePath);

    ui->LAavatar->setPixmap(QPixmap::fromImage(ava));

    pic = QPixmap::fromImage(QImage(picPath));

    ui->LAtext->setWordWrap(true);
    ui->LAtext->setPixmap(pic);

    ui->LAtime->setText(time);
    int picWidth = std::min(width, 400);
    ui->LAtext->resize(QSize(picWidth, computeHeight(picWidth)));
}

QSize Bubble::sizeHint() const
{
    if (is_text) {
        int newWidth = ui->LAtext->width();
        // 计算文本所需的理想高度
        int newHeight = computeHeight(newWidth);
        return QSize(1,std::max(newHeight+ui->LAtime->height()+30, ui->LAavatar->height()+20));
    } else {
        int newWidth = ui->LAtext->width() - 30;

        int picwidth = std::min(newWidth, 400);
        int picHeight = computeHeight(picwidth);

        qDebug() << "pic -- width:" << picwidth << " height: "<< picHeight;
        QPixmap newPic = pic.scaled(picwidth, picHeight, Qt::KeepAspectRatio);
        ui->LAtext->setPixmap(newPic);
        return QSize(1,std::max(picHeight+ui->LAtime->height()+30, ui->LAavatar->height()+20));
    }
}

int Bubble::computeHeight(int width) const
{
    if (is_text) {
        QFontMetrics metrics(ui->LAtext->font());
        return metrics.boundingRect(0, 0, width, INT_MAX, Qt::TextWordWrap, ui->LAtext->text()).height();
    } else {
        return pic.height() * width / pic.width();
    }
}
